package com.xiaot.shopping.product.exception;

import com.xiaot.common.exception.CodeEnum;
import com.xiaot.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author xiaoT
 */
@Slf4j
@RestControllerAdvice
public class ExceptionControllerAdvice {

    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public R validHandle(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        Map<String, Object> result = new HashMap<>();
        bindingResult.getFieldErrors().forEach((i) -> {
            result.put(i.getField(), i.getDefaultMessage());
        });
        return R.error(CodeEnum.VALID).put("data", result);
    }

    @ExceptionHandler(value = Exception.class)
    public R exceptionHandle(Exception e) {
        log.error(e.getMessage(), e);
        return R.error(CodeEnum.UNKNOW);
    }

}
